package com.ygqh.baby.service.weixin.impl;

import java.util.List;
import java.util.Map;

import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.foxinmy.weixin4j.model.WeixinAccount;
import com.foxinmy.weixin4j.mp.message.TemplateMessage;
import com.foxinmy.weixin4j.util.NameValue;
import com.ygqh.baby.ao.Message;
import com.ygqh.baby.ao.WxMessageType;
import com.ygqh.baby.service.weixin.WxTemplateMessageService;
import com.ygqh.baby.service.weixin.model.WxTemplateMessage;
import com.ygqh.baby.service.weixin.templatemessage.SmallTemplateMessageApi;
import com.ygqh.baby.service.weixin.templatemessage.TemplateMessageApi;
import com.ygqh.baby.service.weixin.templatemessage.WeChatTemplateMessageApi;

@Service
public class WxTemplateMessageServiceImpl implements WxTemplateMessageService {

	@Autowired
	private WeChatTemplateMessageApi weChatTemplateMessageApi;
	@Autowired
	private SmallTemplateMessageApi smallTemplateMessageApi;

	@Override
	public Message sendTemplateMessage(WxTemplateMessage info) {
		TemplateMessageApi tempApi = this.getTempApi(info.getMessageType());
		Message message = tempApi.sendTemplateMessage(info.getMessage(), info.getWeixinAccount());
		return message;
	}

	@Override
	public void sendTemplateMessageBatch(List<WxTemplateMessage> messageList) {
		if (CollectionUtils.isNotEmpty(messageList)) {
			for (WxTemplateMessage wxTemplateMessage : messageList) {

				this.sendTemplateMessage(wxTemplateMessage);
			}
		}
	}

	@Override
	public WxTemplateMessage assemblyTemplateMessage(WxMessageType messageType, WeixinAccount weixinAccount, String openId, String url,
			Map<String, NameValue> contentMap) {

		TemplateMessageApi tempApi = this.getTempApi(messageType);
		TemplateMessage message = tempApi.assemblyTemplateMessage(messageType, weixinAccount, openId, url, contentMap);
		
		return new WxTemplateMessage(messageType, weixinAccount, message);
	}

	@Override
	public WxTemplateMessage assemblyTemplateMessage(WxMessageType messageType, WeixinAccount weixinAccount, String head, String remark, String openId,
			String url, String... keyword) {
		// TODO Auto-generated method stub
		return null;
	}

	private TemplateMessageApi getTempApi(WxMessageType messageType) {
		TemplateMessageApi templateMessageApi = null;
		if (messageType.getCode() == 0) {
			templateMessageApi = weChatTemplateMessageApi;
		} else if (messageType.getCode() == 10) {
			templateMessageApi = smallTemplateMessageApi;
		}
		return templateMessageApi;

	}

}
